package com.weirdor.wxchat.module.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import com.weirdor.wxchat.module.entity.SysUser;
import com.weirdor.wxchat.module.entity.SysUserRole;
import com.weirdor.wxchat.module.mapper.SysUserMapper;
import com.weirdor.wxchat.module.service.ISysRoleService;
import com.weirdor.wxchat.module.service.ISysUserRoleService;
import com.weirdor.wxchat.module.service.ISysUserService;
import com.weirdor.wxchat.support.exception.PassionException;
import com.weirdor.wxchat.support.constant.Constant;
import com.xiaoleilu.hutool.util.CollectionUtil;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author weirdor
 * @since 2017-10-31
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {


    @Autowired
    private  SysUserMapper sysUserMapper;

    @Autowired
    private ISysUserRoleService sysUserRoleService;

    @Autowired
    private ISysRoleService sysRoleService;
    @Override
    public SysUser queryByUserName(String username) {
        EntityWrapper<SysUser> ew=new EntityWrapper<>();
        ew.eq("username",username);
        return super.selectOne(ew);
    }

    @Override
    public List<Long> queryAllMenuId(Long userId) {
        return sysUserMapper.queryAllMenuId(userId);
    }

    @Override
    public boolean updatePassword(Long userId, String password, String newPassword) {
        EntityWrapper<SysUser> ew=new EntityWrapper<>();
        ew.where("user_id={0} ",userId," AND password={0} ",password);
        SysUser sysUser=new SysUser();
        sysUser.setPassword(newPassword);
        return super.update(sysUser,ew);
    }
    @Override
    @Transactional
    public void save(SysUser user) {
        user.setCreateTime(new Date());
        //sha256加密
        String salt = RandomStringUtils.randomAlphanumeric(20);
        user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
        user.setSalt(salt);
        super.insert(user);

        //检查角色是否越权
        checkRole(user);

        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }

    @Override
    @Transactional
    public void update(SysUser user) {
        if(StringUtils.isBlank(user.getPassword())){
            user.setPassword(null);
        }else{
            user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
        }
        super.updateById(user);

        //检查角色是否越权
        checkRole(user);

        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }

    @Override
    public List<String> queryAllPerms(Long userId) {
        return sysUserMapper.queryAllPerms(userId);
    }

    @Override
    public void deleteBatch(Long[] userIds) {
        super.deleteBatchIds(CollectionUtil.newArrayList(userIds));
        EntityWrapper<SysUserRole> ew = new EntityWrapper<>();
        ew.where("user_id").in("user_id", userIds);
        sysUserRoleService.delete(ew);
    }

    /**
     * 检查角色是否越权
     */
    private void checkRole(SysUser user){
        //如果不是超级管理员，则需要判断用户的角色是否自己创建
        if(user.getCreateUserId() == Constant.SUPER_ADMIN){
            return ;
        }

        //查询用户创建的角色列表
        List<Long> roleIdList = sysRoleService.queryRoleIdList(user.getCreateUserId());

        //判断是否越权
        if(!roleIdList.containsAll(user.getRoleIdList())){
            throw new PassionException("新增用户所选角色，不是本人创建");
        }
    }
}
